// pages/subject/subject.js
let that,recorderManager,manager,innerAudioContext,myAudio1,
api = new(require('../../utils/api.js')),
headimg = api.getimgurl(),
headaudio = api.getaudiourl(),
audiohead='https://www.jihemu.com/bookapi/myaudio/',
app = getApp(),
util = new(require('../../utils/util.js'));
// const innerAudioContext = wx.createInnerAudioContext();
// plugin = requirePlugin("myPlugin");
// const manager = plugin.getRecordRecognitionManager()
const overallIndex = [{
  key: 'pron_accuracy',
  desc: '准确度',
},
{
  key: 'pron_fluency',
  desc: '流畅度',
},
{
  key: 'pron_completion',
  desc: '完成度',
},
]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    audiohead,
    showid:0,
    list:[],
    headimg,
    headaudio,
    formatCurrentTime: '00:00',
    formatDuration: '00:00',
    luyin:'',
    issaying:!1,
    isplay:!1,
    duration:0,
    currentTime:0,
    isShow:!1,
    PronFluency:0,PronCompletion:0,SuggestedScore:0,useranswer:'',
    islast:!1,
    audioduration:0,list:[],
    isshowmod:!1,
    index:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
    console.log('onLoad');
  
    // let page=getCurrentPages();
    // page = page[page.length-2];
    let cid=options.cid,{duration,formatDuration}=that.data,index=-1,subjectdata=''
    console.log(cid,'cidcidcid');
    that.setData({cid},()=>{
      that.getdata()
    })
    innerAudioContext = wx.createInnerAudioContext();
    myAudio1 = wx.createInnerAudioContext();
    innerAudioContext.onPlay(()=>{
      console.log('正在播放语音')
    })
    
    innerAudioContext.onStop(()=>{
      console.log('语音播放停止')
    })

    innerAudioContext.onError(res=>{
      console.log(res,'AudioContexterr');
    })
    //监听音乐自然播放完
    innerAudioContext.onEnded(res => {
      console.log('播放完！')
      innerAudioContext.seek(0)
      that.setData({isplay:!1,currentTime:0})
    })
    myAudio1.onEnded(res => {
      console.log('myAudio1--播放完！')
      myAudio1.seek(0)
      that.setData({isshowmod:!1,})
      
    })
    const plugin = requirePlugin("myPlugin");
    manager = plugin.getSoeRecorderManager({
      secretId: "AKIDQqgGbmQtqZ9evhCEsGBSXMWUCnPnBGh0",
      secretKey: "FFFPM6bpcARSovkVTDh4RaT5e05uiYBW"
    });

    //开始录音回调
manager.onStart((res) => {
  console.log("成功开始录音识别", res)
 });
 //停止录音回调
 manager.onStop((res) => {
   console.log(res,'sssss');
   let {audioinfo}=that.data
   audioinfo=res.tempFilePath
   that.setData({audioinfo,audioduration:res.duration})
  console.log("录音已停止", res)
  wx.showLoading({
    title: '评测中',
  })
 });
 //错误回调
 manager.onError((res) => {
   wx.hideLoading()
   wx.showModal({
    content:'评测失败，请重新评测',
    showCancel:!1,
  })
  //打印错误
  console.log("打印错误",res)
 })
 manager.onSuccess((res) => {
  //打印识别结果
    wx.hideLoading()
    console.log("打印识别结果",res)
  let {PronFluency,PronCompletion,SuggestedScore} = res,{audioinfo}=that.data
  if(PronFluency<0||PronCompletion<0){
    wx.showModal({
     content:'测试结果不理想，请重新测试一次',
     showCancel:!1,
   })
  }else{
    console.log(111111112222222);
    PronCompletion=(PronCompletion.toFixed(2))*100  //发音完整度，
    PronFluency=(PronFluency.toFixed(2))*100//发音流利度，
    SuggestedScore=SuggestedScore.toFixed(0)
    that.setData({PronCompletion,PronFluency,SuggestedScore},()=>{
      if(audioinfo!=""){
        console.log(111111111333333);
        wx.uploadFile({
          header: {
            'content-type': "application/x-www-form-urlencoded",
            token: getApp().logininfo.Token,
            userid: getApp().logininfo.userid
          },
          url: 'https://www.jihemu.com/bookapi/upload/wx_uploadaudio',

          name: 'upload',
          filePath: audioinfo,
          success(res){
            console.log(res,'auauauaauu')
            const audiores=JSON.parse(res.data);
            if(audiores.issuccess==1){
              that.setData({useranswer:audiores.path},()=>{
                that.aoeEvaluating()
              })
            }else{
              
            }
          }
        })
      }
    })
  }
 });
},
getdata(){
  wx.showLoading({
    title: '加载中',
  })
  let {cid,list}=that.data,subjectdata='',index=-1
  api.Subjectgetlist(cid,res=>{
    wx.hideLoading()
    if(res.data.issuccess==1){
      list=res.data.list
      wx.setNavigationBarTitle({
        title: '1'+'/'+ list.length,
      })
      if(list.length>0){
        subjectdata=list[0]
        index=0
      }
      that.setData({list,subjectdata,index},()=>{
          let id =subjectdata.id
          api.getEvaluatingDetail(id,res=>{
            if(res.data.issuccess==1){
              if(res.data.data){
                let {data} =res.data
                that.setData({isShow:!0,useranswer:data.useranswer,PronFluency:data.fluency,PronCompletion:data.integrity,SuggestedScore:data.totalscore})
              }
              console.log(res.data.data,'getEvaluatingDetailgetEvaluatingDetail');
            }
          })
          if(subjectdata.audiosrc!=null&&subjectdata.audiosrc!=''){
            if(subjectdata.audiosrc.indexOf('http')==-1){
              subjectdata.audiosrc=headaudio+subjectdata.audiosrc
            }
            that.changenewaudio(subjectdata)
          }
          // if(subjectdata.audiosrc.indexOf('http')==-1){
          //   subjectdata.audiosrc=headaudio+subjectdata.audiosrc
          // }
          console.log( subjectdata.audiosrc,' subjectdata.audiosrc subjectdata.audiosrc');
          // that.changenewaudio(subjectdata)
      })
    }
  })
  let {user} =app.logininfo
  that.setData({user})
  console.log(app.logininfo.user,'apppppppp');
},
aoeEvaluating(){
  let{PronFluency,PronCompletion,SuggestedScore,subjectdata,useranswer,islast,audioduration}=that.data
  console.log(audioduration,'audiodurationaudiodurationaudioduration');
  console.log(PronFluency,'PronFluencyPronFluencyPronFluency');
  console.log(PronCompletion,'PronCompletion');
  console.log(SuggestedScore,'SuggestedScore');
  console.log(subjectdata,'subjectdatasubjectdatasubjectdata');
  api.aoeEvaluating({audioduration,integrity:PronCompletion,fluency:PronFluency,useranswer,id:subjectdata.id,totalscore:SuggestedScore,type:subjectdata.type},res=>{
    if(res.data.issuccess==1){
      console.log(res.data,'aoeEvaluatingaoeEvaluating');
      that.setData({isShow:!0},()=>{
        if(subjectdata.type=="FOLLOWUP"){
          that.resultplay()
        }
      })
      if(islast){
        wx.navigateBack()
      }
    }else{
      if(islast){
        wx.navigateBack()
      }
    }
  })
},
// 评分结果语音
resultplay(){
  myAudio1.title='c'
  let {SuggestedScore}=that.data
  if(SuggestedScore>=90){
    myAudio1.src ="https://www.jihemu.com/bookapi/minipaudio/excellent.mp3"
  }else if(SuggestedScore<90&&SuggestedScore>=80){
    myAudio1.src ="https://www.jihemu.com/bookapi/minipaudio/awsome.mp3"
  }else if(SuggestedScore<80&&SuggestedScore>=60){
    myAudio1.src ="https://www.jihemu.com/bookapi/minipaudio/goodjob.mp3"
  }else{
    myAudio1.src ="https://www.jihemu.com/bookapi/minipaudio/repeatagain.mp3"
  }
  // myAudio.src = a
  myAudio1.play()
  that.setData({isshowmod:!0})
},
  //播放
  play(e){
    let {isplay}=that.data,{title,audiosrc}=e.currentTarget.dataset
    console.log(audiosrc,'audiosrcaudiosrcaudiosrc');
    innerAudioContext.title=title
    // if (!innerAudioContext.src) {
      innerAudioContext.title = title;
      innerAudioContext.src = audiosrc
    // }
    if(!isplay){
      innerAudioContext.play()
      setTimeout(() => {
        console.log(innerAudioContext.paused)
    }, 100)
      that.setData({isplay:!0})
    }else{
      innerAudioContext.pause()
      that.setData({isplay:!1})
    }
  },
  woaudiosrc(){
    wx.showModal({
      title: '提示',
      content:'该题目无原音',
      showCancel:false
    })
  },
  changenewaudio(audio){
    console.log('changenewaudio', audio)
    innerAudioContext.stop();
    innerAudioContext.src=audio.audiosrc;
    innerAudioContext.title=audio.title||'a';
    innerAudioContext.play();
    that.setData({
      isplay: !0,
      // duration, formatDuration
    })
    innerAudioContext.onCanplay(()=>{
      that.initaudio(innerAudioContext.duration)
      
    })

  },
  initaudio(duration){
    console.log('initaudio')
    let formatDuration = '';
    wx.hideLoading();
     // innerAudioContext.duration
      duration = innerAudioContext.duration
      duration = Math.ceil(duration)
      formatDuration = that.formatSeconds(duration)
      that.setData({
        // isplay: !0,
        duration, formatDuration
      })

      innerAudioContext.onTimeUpdate(()=>{
        let currentTime = Math.ceil(innerAudioContext.currentTime);
        that.setData({
          duration:innerAudioContext.duration,
          formatDuration:that.formatSeconds(innerAudioContext.duration),
          currentTime ,
          formatCurrentTime: that.formatSeconds(currentTime),
        })
      })
    //监听音乐暂停
    innerAudioContext.onPause(res => {
      that.setData({
        isplay: !1
      })
    })
    //监听音乐自然播放完
    // innerAudioContext.onEnded(res => {
    //   console.log('播放完！')
    //   innerAudioContext.seek(0)
    //   console.log('hhhhhhhhh');
    //   that.setData({isplay: !1,currentTime:0})
    // })
  },
  /**
   * 进度条事件
   */
  sliderChange(e) {
    let percent = e.detail.value,
      {
        duration
      } = that.data;
    if (innerAudioContext.paused) {
      innerAudioContext.seek(percent)
    } else {
      innerAudioContext.seek(percent)
    }
  },
  // 录音
  say(e){
    innerAudioContext.pause()
    let {subjectdata,issaying} = that.data
    myAudio1.title="d"
    let  options = {
      content:subjectdata.contents,
      evalMode: subjectdata.evalmode,
      serverType:subjectdata.servertype,
      textMode: 0,
    }
    if(!issaying){
      wx.authorize({
        scope: 'scope.record',
        success() {
          console.log("录音授权成功");
          //第一次成功授权后 状态切换为2
          that.setData({
            status: 2,
          })
          // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
          // wx.startRecord();
          that.setData({issaying:!0,isplay:!1},()=>{
            myAudio1.src ="https://www.jihemu.com/bookapi/minipaudio/luyin.mp3"
            myAudio1.play()
          })
          manager.start(options);//使用新版录音接口，可以获取录音文件
        },
        fail(){
          console.log("第一次录音授权失败");
          wx.showModal({
            title: '提示',
            content: '您未授权录音，功能将无法使用',
            showCancel: true,
            confirmText: "授权",
            confirmColor: "#52a2d8",
            success: function (res) {
              if (res.confirm) {
                //确认则打开设置页面（重点）
                wx.openSetting({
                  success: (res) => {
                    console.log(res.authSetting);
                    if (!res.authSetting['scope.record']) {
                      //未设置录音授权
                      console.log("未设置录音授权");
                      wx.showModal({
                        title: '提示',
                        content: '您未授权录音，功能将无法使用',
                        showCancel: false,
                        success: function (res) {
  
                        },
                      })
                    } else {
                      //第二次才成功授权
                      console.log("设置录音授权成功");
                      that.setData({
                        status: 2,
                      })
                      // that.setData({issaying:!0,isplay:!1})
                      // manager.start(options)
                    }
                  },
                  fail: function () {
                    console.log("授权设置录音失败");
                  }
                })
              } else if (res.cancel) {
                console.log("cancel");
              }
            },
            fail: function () {
              console.log("openfail");
            }
          })
        }
      })
    }else{
      that.setData({issaying:!1})
      manager.stop()
    }
  },

  end(e){
    console.log(e,'end');
    that.setData({issaying:!1})
    manager.stop()

  },
    /**
   *  时间格式化
   */
  formatSeconds(value) {
    if(isNaN(value)) return "00:00";
    var secondTime = parseInt(value); // 秒
    var minuteTime = 0; // 分
    var hourTime = 0; // 小时
    if (secondTime >= 60) { //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
     
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime >= 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60);
       
      }
    }
    minuteTime = minuteTime + hourTime * 60;
    if (secondTime < 10) {
      secondTime = "0" + secondTime
    }
    if (minuteTime < 10) {
      minuteTime = "0" + minuteTime
    }
    var result = minuteTime + ':' + secondTime;
    
    return result;
  },
  preheadImg:function(e){
    var src = e.currentTarget.dataset.src;
    let headimg=[]
    headimg.push(src)
    // var imglist = this.data.imglist;
    wx.previewImage({
      current:src,     //当前图片地址
      urls: headimg,               //所有要预览的图片的地址集合 数组形式
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  getdetail(){
    let {subjectdata} = that.data
    let id = subjectdata.id
    api.getEvaluatingDetail(id,res=>{
      if(res.data.issuccess==1){
        console.log(res.data.data,'res.data.datares.data.data');
        if(res.data.data){
          let {data} = res.data
          that.setData({isShow:!0,useranswer:data.useranswer,PronFluency:data.fluency,PronCompletion:data.integrity,SuggestedScore:data.totalscore})
        }else{
          that.setData({isShow:!1})
        }
      }
    })
  },
  clicknext(index){
    let {list,subjectdata,PronFluency,PronCompletion,SuggestedScore,useranswer}=that.data
    if(index==list.length-1){
      if(useranswer==''){
        wx.showModal({
          title: '提示',
          content:subjectdata.type=='FOLLOWUP'?'请先跟读':'请先答题',
          showCancel:!1
        })
        return
      }else{
        that.setData({islast:!0},()=>{
          if(subjectdata.type!="FOLLOWUP"){
            that.aoeEvaluating()
          }else{
            wx.switchTab({
              url: '../share/share',
            })
            // wx.navigateBack()
          }
        })
      }
    }else{
      index=index+1
    
      if(useranswer==''){
        wx.showModal({
          title: '提示',
          content:subjectdata.type=='FOLLOWUP'?'请先跟读':'请先答题',
          showCancel:!1
        })
      }else{
        wx.setNavigationBarTitle({
          title: index+1+'/'+ list.length,
        })
        if(subjectdata.type!="FOLLOWUP"){
          that.aoeEvaluating()
        }
        subjectdata=list[index]
        console.log(subjectdata,'subjectdatasubjectdata');
        if(subjectdata.audiosrc!=null&&subjectdata.audiosrc!=''){
          if(subjectdata.audiosrc.indexOf('http')==-1){
            subjectdata.audiosrc=headaudio+subjectdata.audiosrc
          }
          that.changenewaudio(subjectdata)
        }
        that.setData({useranswer:'',isShow:!1,subjectdata,index},()=>{
         that.getdetail()
        })
      }
    }
  },
  switchSubject(e){
    let {index,type} = e.currentTarget.dataset,{list,subjectdata,PronFluency,PronCompletion,SuggestedScore,useranswer}=that.data
    
    if(type=='next'){
      that.clicknext(index)
    }else{
      if(index==0){
        wx.showToast({
          title: '已经是第一题了',
          icon:'none'
        })
        return
      }else{
        index=index-1
        wx.setNavigationBarTitle({
          title: index+1+'/'+ list.length,
        })
        if(subjectdata.type!="FOLLOWUP"){
          that.aoeEvaluating()
        }
        subjectdata=list[index]
        if(subjectdata.audiosrc!=null&&subjectdata.audiosrc!=''){
          if(subjectdata.audiosrc.indexOf('http')==-1){
            subjectdata.audiosrc=headaudio+subjectdata.audiosrc
          }
          that.changenewaudio(subjectdata)
        }
        subjectdata.title=subjectdata.title.replace(/&#39;/g,'\'');
        subjectdata.contents=subjectdata.contents.replace(/&#39;/g,'\'');
        that.setData({useranswer:'',isShow:!1,subjectdata,index},()=>{
         that.getdetail()
        })
      }
    }
  },
  // switchSubject(e){
  //   let {index,type} = e.currentTarget.dataset,{list,subjectdata,PronFluency,PronCompletion,SuggestedScore,useranswer}=that.data
  //   if(type=='next'){
  //     if(index==list.length-1){
  //       if(useranswer==''){
  //         wx.showModal({
  //           title: '提示',
  //           content:subjectdata.type=='FOLLOWUP'?'请先跟读':'请先答题',
  //           showCancel:!1
  //         })
  //         return
  //       }else{
  //         that.setData({islast:!0},()=>{
  //           that.aoeEvaluating()
  //         })
  //       }
  //     }else{
  //       index=index+1
  //       subjectdata=list[index]
  //       let id = subjectdata.id
  //       if(useranswer==''){
  //         wx.showModal({
  //           title: '提示',
  //           content:subjectdata.type=='FOLLOWUP'?'请先跟读':'请先答题',
  //           showCancel:!1
  //         })
  //         return
  //       }else{
  //         that.aoeEvaluating()
  //         api.getEvaluatingDetail(id,res=>{
  //           if(res.data.issuccess==1){
  //             console.log(res.data.data,'res.data.datares.data.data');
  //             if(res.data.data){
  //               let {data} = res.data
  //               that.setData({isShow:!0,useranswer:data.useranswer,PronFluency:data.fluency,PronCompletion:data.integrity,SuggestedScore:data.totalscore})
  //             }else{
  //               that.setData({isShow:!1})
  //             }
  //             console.log(res.data.data,'getEvaluatingDetailgetEvaluatingDetail');
  //           }
  //         })
  //         if(subjectdata.audiosrc!=null&&subjectdata.audiosrc!=''){
  //           if(subjectdata.audiosrc.indexOf('http')==-1){
  //             subjectdata.audiosrc=headaudio+subjectdata.audiosrc
  //           }
  //           that.changenewaudio(subjectdata)
  //         }
  //       }
  //     }
  //   }else{
  //     if(index==0){
  //       wx.showToast({
  //         title: '已经是第一题了',
  //         icon:'none'
  //       })
  //       return
  //     }else{
  //       index=index-1
  //       subjectdata=list[index]
  //       let id = subjectdata.id
  //       if(subjectdata.audiosrc!=null&&subjectdata.audiosrc!=''){
  //         if(subjectdata.audiosrc.indexOf('http')==-1){
  //           subjectdata.audiosrc=headaudio+subjectdata.audiosrc
  //         }
  //         that.changenewaudio(subjectdata)
  //       }
  //       api.getEvaluatingDetail(id,res=>{
  //         if(res.data.issuccess==1){
  //           if(res.data.data){
  //             let {data} = res.data
  //             that.setData({isShow:!0,useranswer:data.useranswer,PronFluency:data.fluency,PronCompletion:data.integrity,SuggestedScore:data.totalscore})
  //           }else{
  //             that.setData({isShow:!1})
  //           }
  //           console.log(res.data.data,'getEvaluatingDetailgetEvaluatingDetail');
  //         }
  //       })
  //     }
  //   }
  //   that.setData({subjectdata,index})
  // },
  choice(e){
    let {value,answer} = e.currentTarget.dataset,{useranswer,list,subjectdata,index}=that.data
    if(useranswer==value) return
    that.setData({useranswer:value},()=>{
      if(value==answer){
        that.clicknext(index)
      }
    })
  },
  playme(){
    let {useranswer,subjectdata} = that.data
      if(useranswer==''){
        wx.showToast({
          title: '你还没有发布过语音测评',
          icon:'none'
        })
      }else{
        let data={audiosrc:audiohead+useranswer,title:'b'}
        that.changenewaudio(data)
      }
  },
  hidemod(){
    that.setData({isshowmod:!1})
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
    that.setData({duration:0,formatDuration:'00:00'})
    // innerAudioContext.offCanplay()
    innerAudioContext.destroy()
    // innerAudioContext.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    that.setData({duration:0,formatDuration:'00:00'})
    // innerAudioContext.offCanplay()
    innerAudioContext.destroy()
    // innerAudioContext.stop()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})